package com.example.bgdharaniPlayer.ui;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.bgdharaniPlayer.R;
import com.example.bgdharaniPlayer.model.AudioTrack;
import com.example.bgdharaniPlayer.model.Playlist;
import com.example.bgdharaniPlayer.service.MusicService;
import com.example.bgdharaniPlayer.util.PlaylistStorage;

import java.io.File;

public class PlaylistActivity extends AppCompatActivity {

    private static final String TAG = "PlaylistActivity";
    private static final int REQUEST_PICK_AUDIO = 1;
    private static final String PREFS_NAME = "AudioPickerPrefs";
    private static final String KEY_LAST_DIRECTORY = "last_directory";

    private RecyclerView recyclerViewPlaylist;
    private Button btnAddTrack;
    private PlaylistAdapter adapter;
    private Playlist playlist;
    private String lastDirectoryPath = null;

    private MusicService musicService;
    private boolean isBound = false;

    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MusicService.MusicBinder binder = (MusicService.MusicBinder) service;
            musicService = binder.getService();
            isBound = true;
            
            // 获取当前播放列表
            if (musicService != null && playlist.isEmpty()) {
                // 如果服务中已有播放列表，则使用它
                if (musicService.getCurrentTrack() != null) {
                    updatePlaylistFromService();
                }
            } else {
                // 否则，将当前播放列表设置到服务中
                updatePlaylistWithoutAffectingPlayback();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            musicService = null;
            isBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_playlist);

        // 获取传递的播放列表 ID
        String playlistId = getIntent().getStringExtra("playlist_id");
        
        // 从存储中加载播放列表
        if (playlistId != null) {
            // 加载指定 ID 的播放列表，但不设置为当前选中的播放列表
            playlist = PlaylistStorage.loadPlaylist(this, playlistId);
        } else {
            // 加载当前选中的播放列表
            playlist = PlaylistStorage.loadPlaylist(this);
        }
        
        Log.d("PlaylistActivity", "加载播放列表 ID: " + (playlistId != null ? playlistId : "当前选中") + 
                "，名称: " + playlist.getName() + "，共 " + playlist.size() + " 个音频");

        initViews();
        setupListeners();
        bindMusicService();
    }

    private TextView tvPlaylistTitle;
    
    private void initViews() {
        recyclerViewPlaylist = findViewById(R.id.recyclerViewPlaylist);
        btnAddTrack = findViewById(R.id.btnAddTrack);
        tvPlaylistTitle = findViewById(R.id.tvPlaylistTitle);

        // 设置播放列表标题
        tvPlaylistTitle.setText(playlist.getName());
        
        // 设置RecyclerView
        recyclerViewPlaylist.setLayoutManager(new LinearLayoutManager(this));
        adapter = new PlaylistAdapter(playlist.getTracks(), this::showTrackSettingsDialog, this::removeTrack);
        recyclerViewPlaylist.setAdapter(adapter);
        
        // 设置拖放功能
        setupItemTouchHelper();
    }
    
    private void setupItemTouchHelper() {
        // 创建 ItemTouchHelper 来处理拖放操作
        ItemTouchHelper.Callback callback = new ItemTouchHelper.SimpleCallback(
                ItemTouchHelper.UP | ItemTouchHelper.DOWN, // 允许上下拖动
                0) { // 不允许滑动删除
            
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, 
                                 @NonNull RecyclerView.ViewHolder viewHolder, 
                                 @NonNull RecyclerView.ViewHolder target) {
                // 获取拖动项和目标项的位置
                int fromPosition = viewHolder.getAdapterPosition();
                int toPosition = target.getAdapterPosition();
                
                if (fromPosition < 0 || toPosition < 0 || 
                    fromPosition >= playlist.size() || toPosition >= playlist.size()) {
                    return false;
                }
                
                // 移动列表项
                AudioTrack movedItem = playlist.getTracks().remove(fromPosition);
                playlist.getTracks().add(toPosition, movedItem);
                
                // 通知适配器项目已移动
                adapter.notifyItemMoved(fromPosition, toPosition);
                
                // 检查是否有正在播放的内容，如果有，不更新服务中的播放列表
                updatePlaylistWithoutAffectingPlayback();
                
                // 保存播放列表到存储
                PlaylistStorage.savePlaylist(PlaylistActivity.this, playlist);
                Log.d("PlaylistActivity", "重新排序后保存播放列表，共 " + playlist.size() + " 个音频");
                
                return true;
            }
            
            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                // 不实现滑动删除功能
            }
            
            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                super.onSelectedChanged(viewHolder, actionState);
                // 当项目被选中进行拖动时，改变其外观
                if (actionState == ItemTouchHelper.ACTION_STATE_DRAG && viewHolder != null) {
                    viewHolder.itemView.setAlpha(0.7f);
                }
            }
            
            @Override
            public void clearView(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                // 当拖动结束时，恢复项目的外观
                viewHolder.itemView.setAlpha(1.0f);
            }
        };
        
        // 将 ItemTouchHelper 附加到 RecyclerView
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
        itemTouchHelper.attachToRecyclerView(recyclerViewPlaylist);
    }

    private void setupListeners() {
        btnAddTrack.setOnClickListener(v -> pickAudioFile());
        
        // 添加播放列表标题点击监听器
        tvPlaylistTitle.setOnClickListener(v -> showEditPlaylistNameDialog());
        
        // 添加切换播放此列表按钮的点击监听器
        Button btnPlayThisList = findViewById(R.id.btnPlayThisList);
        btnPlayThisList.setOnClickListener(v -> {
            // 保存当前选中的播放列表ID
            PlaylistStorage.saveCurrentPlaylistId(this, playlist.getId());
            
            // 返回主界面并立即播放
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("action", "play_now");
            intent.putExtra("playlist_id", playlist.getId());
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
        });
    }
    
    /**
     * 显示编辑播放列表名称的对话框
     */
    private void showEditPlaylistNameDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.edit_playlist_name);
        
        // 创建输入框
        final EditText input = new EditText(this);
        input.setText(playlist.getName());
        input.setSelectAllOnFocus(true);
        input.setSingleLine(true);
        
        // 设置输入框的布局参数
        LayoutInflater inflater = this.getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.dialog_add_playlist, null);
        EditText etPlaylistName = dialogView.findViewById(R.id.etPlaylistName);
        etPlaylistName.setText(playlist.getName());
        etPlaylistName.setSelectAllOnFocus(true);
        
        builder.setView(dialogView);
        
        // 设置按钮
        builder.setPositiveButton(R.string.save, (dialog, which) -> {
            String newName = etPlaylistName.getText().toString().trim();
            if (!newName.isEmpty()) {
                playlist.setName(newName);
                tvPlaylistTitle.setText(newName);
                
                // 保存播放列表到存储
                PlaylistStorage.savePlaylist(this, playlist);
                Log.d(TAG, "修改播放列表名称为: " + newName);
                
                // 修改名称不影响播放，所以不需要更新服务中的播放列表
            }
        });
        builder.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.cancel());
        
        // 显示对话框
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void bindMusicService() {
        Intent intent = new Intent(this, MusicService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private void updatePlaylistFromService() {
        // 这个方法将从服务中获取播放列表
        // 在实际应用中，你可能需要实现一个更复杂的逻辑来同步播放列表
        if (musicService != null) {
            // 假设MusicService有一个方法可以获取完整的播放列表
            // 这里简化处理，实际应用中可能需要更复杂的逻辑
            adapter.notifyDataSetChanged();
        }
    }
    
    /**
     * 更新播放列表但不影响当前播放
     * 此方法确保在编辑播放列表时不会干扰正在播放的内容
     */
    private void updatePlaylistWithoutAffectingPlayback() {
        if (isBound && musicService != null) {
            // 检查服务是否正在播放
            boolean isPlaying = musicService.isPlaying();
            int currentTrackIndex = musicService.getCurrentTrackIndex();
            AudioTrack currentTrack = musicService.getCurrentTrack();
            
            if (isPlaying && currentTrack != null) {
                // 记录当前播放状态，但不更改服务中的播放列表
                Log.d(TAG, "保持当前播放状态，不更新服务中的播放列表");
            } else {
                // 如果没有正在播放的内容，可以安全地更新播放列表
                musicService.setPlaylist(playlist);
                Log.d(TAG, "没有正在播放的内容，更新服务中的播放列表");
            }
        }
    }

    private void pickAudioFile() {
        // 显示选择对话框，让用户选择文件选择方式
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择音频文件");
        
        // 创建选项列表
        String[] options = {
            "从音乐文件夹选择",
            "从下载文件夹选择",
            "从存储根目录选择",
            "从最近目录选择"
        };
        
        builder.setItems(options, (dialog, which) -> {
            switch (which) {
                case 0:
                    // 从音乐文件夹选择
                    openFilePickerWithPath(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath());
                    break;
                case 1:
                    // 从下载文件夹选择
                    openFilePickerWithPath(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
                    break;
                case 2:
                    // 从存储根目录选择
                    openFilePickerWithPath(Environment.getExternalStorageDirectory().getAbsolutePath());
                    break;
                case 3:
                    // 从最近目录选择
                    openFilePickerWithPath(getLastDirectory());
                    break;
            }
        });
        
        builder.show();
    }
    
    private String getLastDirectory() {
        // 尝试恢复上次的目录路径
        if (lastDirectoryPath == null) {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
            lastDirectoryPath = prefs.getString(KEY_LAST_DIRECTORY, null);
        }
        
        // 如果没有上次的目录，返回音乐文件夹
        if (lastDirectoryPath == null) {
            return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getAbsolutePath();
        }
        
        return lastDirectoryPath;
    }
    
    private void openFilePickerWithPath(String path) {
        // 记录选择的路径
        Log.d(TAG, "打开文件选择器，路径: " + path);
        
        try {
            // 使用 ACTION_OPEN_DOCUMENT 打开文件选择器
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("audio/*");
            
            // 启用多选功能
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            
            // 设置初始目录（注意：这个功能在某些设备上可能不起作用）
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                try {
                    // 使用 DocumentFile 创建正确的 URI
                    File directory = new File(path);
                    if (directory.exists() && directory.isDirectory()) {
                        // 尝试使用 SAF 兼容的方式获取 URI
                        Uri externalUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                        Uri directoryUri = DocumentsContract.buildDocumentUri(
                            "com.android.externalstorage.documents",
                            "primary:" + path.substring(path.indexOf("/storage/emulated/0/") + "/storage/emulated/0/".length())
                        );
                        intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, directoryUri);
                        Log.d(TAG, "设置初始目录 URI: " + directoryUri);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "设置初始目录失败: " + e.getMessage());
                }
            }
            
            // 设置默认视图为列表视图，不使用缩略图视图
            intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
            intent.putExtra("android.content.extra.FANCY", false);
            intent.putExtra("android.content.extra.SHOW_FILESIZE", true);
            
            // 允许多次访问所选文档
            intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            
            startActivityForResult(intent, REQUEST_PICK_AUDIO);
        } catch (Exception e) {
            Log.e(TAG, "打开文件选择器失败: " + e.getMessage());
            // 如果失败，回退到默认文件选择器
            openDefaultFilePicker();
        }
    }
    
    private void openDefaultFilePicker() {
        try {
            // 使用 ACTION_OPEN_DOCUMENT 打开文件选择器
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("audio/*");
            
            // 启用多选功能
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            
            // 设置默认视图为列表视图，不使用缩略图视图
            intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
            intent.putExtra("android.content.extra.FANCY", false);
            intent.putExtra("android.content.extra.SHOW_FILESIZE", true);
            
            // 允许多次访问所选文档
            intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            
            startActivityForResult(intent, REQUEST_PICK_AUDIO);
        } catch (Exception e) {
            // 如果 ACTION_OPEN_DOCUMENT 不可用，回退到 ACTION_GET_CONTENT
            Log.e(TAG, "ACTION_OPEN_DOCUMENT 不可用，回退到 ACTION_GET_CONTENT: " + e.getMessage());
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("audio/*");
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            startActivityForResult(intent, REQUEST_PICK_AUDIO);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PICK_AUDIO && resultCode == RESULT_OK && data != null) {
            // 处理多选文件的情况
            if (data.getClipData() != null) {
                // 多选文件
                int count = data.getClipData().getItemCount();
                Log.d("PlaylistActivity", "选择了 " + count + " 个音频文件");
                
                for (int i = 0; i < count; i++) {
                    Uri audioUri = data.getClipData().getItemAt(i).getUri();
                    if (audioUri != null) {
                        processAudioUri(audioUri);
                    }
                }
            } else if (data.getData() != null) {
                // 单选文件
                Uri audioUri = data.getData();
                processAudioUri(audioUri);
            }
            
            // 保存播放列表到存储
            PlaylistStorage.savePlaylist(this, playlist);
            Log.d("PlaylistActivity", "添加音频后保存播放列表，共 " + playlist.size() + " 个音频");
            
            // 更新适配器
            adapter.notifyDataSetChanged();
            
            // 更新服务中的播放列表，但不影响当前播放
            updatePlaylistWithoutAffectingPlayback();
        }
    }
    
    // 处理单个音频URI的方法
    private void processAudioUri(Uri audioUri) {
        String path = getPathFromUri(audioUri);
        String fileName = new File(path).getName();
        
        // 保存选择的文件所在的目录路径
        File parentDir = new File(path).getParentFile();
        if (parentDir != null) {
            lastDirectoryPath = parentDir.getAbsolutePath();
            // 保存到 SharedPreferences
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(KEY_LAST_DIRECTORY, lastDirectoryPath);
            editor.apply();
            Log.d("PlaylistActivity", "保存上次选择的目录: " + lastDirectoryPath);
        }
        
        AudioTrack track = new AudioTrack(path, fileName);
        playlist.addTrack(track);
        Log.d("PlaylistActivity", "添加音频: " + fileName);
    }

    private String getPathFromUri(Uri uri) {
        // 使用ContentResolver获取文件的实际路径
        String path = null;
        
        try {
            // 首先尝试使用MediaStore查询
            String[] projection = {MediaStore.Audio.Media.DATA};
            android.database.Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
            
            if (cursor != null && cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
                path = cursor.getString(column_index);
                cursor.close();
                
                if (path != null) {
                    Log.d("PlaylistActivity", "通过MediaStore获取路径: " + path);
                    return path;
                }
            }
            
            // 如果MediaStore查询失败，尝试使用DocumentFile
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                // 获取持久权限
                final int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION;
                getContentResolver().takePersistableUriPermission(uri, takeFlags);
                
                // 尝试使用DocumentFile获取文件名
                androidx.documentfile.provider.DocumentFile documentFile = 
                        androidx.documentfile.provider.DocumentFile.fromSingleUri(this, uri);
                
                if (documentFile != null && documentFile.exists()) {
                    String fileName = documentFile.getName();
                    if (fileName != null) {
                        // 创建一个临时文件来存储音频内容
                        java.io.File cacheDir = new java.io.File(getExternalCacheDir(), "audio_cache");
                        if (!cacheDir.exists()) {
                            cacheDir.mkdirs();
                        }
                        
                        java.io.File outputFile = new java.io.File(cacheDir, fileName);
                        
                        try {
                            // 复制文件内容
                            java.io.InputStream inputStream = getContentResolver().openInputStream(uri);
                            java.io.FileOutputStream outputStream = new java.io.FileOutputStream(outputFile);
                            
                            byte[] buffer = new byte[4096];
                            int bytesRead;
                            while ((bytesRead = inputStream.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, bytesRead);
                            }
                            
                            inputStream.close();
                            outputStream.close();
                            
                            path = outputFile.getAbsolutePath();
                            Log.d("PlaylistActivity", "通过复制文件获取路径: " + path);
                            return path;
                        } catch (Exception e) {
                            Log.e("PlaylistActivity", "复制文件失败: " + e.getMessage());
                        }
                    }
                }
            }
            
            // 最后尝试直接使用URI路径
            path = uri.getPath();
            Log.d("PlaylistActivity", "使用URI路径: " + path);
            
        } catch (Exception e) {
            Log.e("PlaylistActivity", "获取文件路径失败: " + e.getMessage());
        }
        
        // 如果所有方法都失败，返回URI的字符串表示
        if (path == null) {
            path = uri.toString();
            Log.d("PlaylistActivity", "使用URI字符串: " + path);
        }
        
        return path;
    }

    private void onTrackClick(int position) {
        if (isBound) {
            // 确保停止当前播放
            if (musicService.isPlaying()) {
                musicService.stop();
            }
            
            // 将当前编辑的播放列表设置为当前选中的播放列表
            PlaylistStorage.saveCurrentPlaylistId(this, playlist.getId());
            Log.d(TAG, "切换当前播放列表为: " + playlist.getName() + ", ID: " + playlist.getId());
            
            // 设置播放列表到服务中
            musicService.setPlaylist(playlist);
            
            // 播放选中的曲目
            musicService.play(position);
            Log.d(TAG, "点击播放曲目，位置: " + position + ", 标题: " + playlist.getTrack(position).getTitle());
        }
    }

    private void showTrackSettingsDialog(int position) {
        AudioTrack track = playlist.getTrack(position);
        if (track == null) return;

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_track_settings, null);
        
        TextView tvTitle = view.findViewById(R.id.tvDialogTitle);
        android.widget.SeekBar seekBarSpeed = view.findViewById(R.id.seekBarSpeed);
        TextView tvSpeedValue = view.findViewById(R.id.tvSpeedValue);
        EditText etRepeatCount = view.findViewById(R.id.etRepeatCount);
        Button btnPlay = view.findViewById(R.id.btnPlay);
        Button btnSave = view.findViewById(R.id.btnSave);
        // 取消按钮已从布局中移除

        tvTitle.setText(track.getTitle());
        
        // 设置播放速度，范围0.5x-16.0x
        // 将播放速度映射到进度条的值（0-100）
        // 使用对数映射，使得低速度区间更精细
        float maxSpeed = 16.0f;
        float minSpeed = 0.5f;
        float speed1 = track.getPlaybackSpeed();
        
        // 使用对数映射，将 0.5-32 映射到 0-100
        int speedProgress;
        if (speed1 <= 1.0f) {
            // 0.5-1.0 映射到 0-25
            speedProgress = (int)((speed1 - minSpeed) / (1.0f - minSpeed) * 25);
        } else if (speed1 <= 4.0f) {
            // 1.0-4.0 映射到 25-50
            speedProgress = (int)(25 + (speed1 - 1.0f) / (4.0f - 1.0f) * 25);
        } else {
            // 4.0-16.0 映射到 50-100
            speedProgress = (int)(50 + (speed1 - 4.0f) / (16.0f - 4.0f) * 50);
        }
        
        seekBarSpeed.setProgress(speedProgress);
        tvSpeedValue.setText(String.format("%.1fx", speed1));
        
        etRepeatCount.setText(String.valueOf(track.getRepeatCount()));

        seekBarSpeed.setOnSeekBarChangeListener(new android.widget.SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(android.widget.SeekBar seekBar, int progress, boolean fromUser) {
                float speed2;
                if (progress <= 25) {
                    // 0-25 映射到 0.5-1.0
                    speed2 = 0.5f + (progress / 25f) * 0.5f;
                } else if (progress <= 50) {
                    // 25-50 映射到 1.0-4.0
                    speed2 = 1.0f + ((progress - 25) / 25f) * 3.0f;
                } else {
                    // 50-100 映射到 4.0-16.0
                    speed2 = 4.0f + ((progress - 50) / 50f) * 12.0f;
                }
                tvSpeedValue.setText(String.format("%.1fx", speed2));
            }

            @Override
            public void onStartTrackingTouch(android.widget.SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(android.widget.SeekBar seekBar) {}
        });

        AlertDialog dialog = builder.setView(view).create();

        // 设置播放按钮点击事件
        btnPlay.setOnClickListener(v -> {
            // 播放当前曲目
            onTrackClick(position);
        });

        btnSave.setOnClickListener(v -> {
            float speed;
            int progress = seekBarSpeed.getProgress();
            if (progress <= 25) {
                // 0-25 映射到 0.5-1.0
                speed = 0.5f + (progress / 25f) * 0.5f;
            } else if (progress <= 50) {
                // 25-50 映射到 1.0-4.0
                speed = 1.0f + ((progress - 25) / 25f) * 3.0f;
            } else {
                // 50-100 映射到 4.0-16.0
                speed = 4.0f + ((progress - 50) / 50f) * 12.0f;
            }
            int repeatCount;
            try {
                repeatCount = Integer.parseInt(etRepeatCount.getText().toString());
                if (repeatCount < 1) repeatCount = 1;
            } catch (NumberFormatException e) {
                repeatCount = 1;
            }

            track.setPlaybackSpeed(speed);
            track.setRepeatCount(repeatCount);
            
            // 检查是否正在播放这个曲目
            boolean isCurrentlyPlaying = false;
            if (isBound && musicService.isPlaying() && musicService.getCurrentTrackIndex() == position) {
                isCurrentlyPlaying = true;
            }
            
            // 如果当前正在播放这个曲目，只更新播放速度而不改变播放列表
            if (isCurrentlyPlaying) {
                // 使用新方法直接更新播放速度，无需暂停和重新播放
                musicService.updateCurrentPlaybackSpeed(speed);
                Log.d("PlaylistActivity", "已实时更新当前播放曲目的速度为: " + speed);
            }
            
            // 保存播放列表到存储
            PlaylistStorage.savePlaylist(this, playlist);
            Log.d("PlaylistActivity", "修改音频设置后保存播放列表，共 " + playlist.size() + " 个音频");
            
            adapter.notifyItemChanged(position);
            dialog.dismiss();
        });

        // 取消按钮已从布局中移除，不再需要设置点击监听器

        dialog.show();
    }

    private void removeTrack(int position) {
        if (position >= 0 && position < playlist.size()) {
            // 检查是否正在播放这个曲目
            boolean isCurrentlyPlaying = false;
            int currentPlayingIndex = -1;
            
            if (isBound && musicService != null) {
                currentPlayingIndex = musicService.getCurrentTrackIndex();
                isCurrentlyPlaying = musicService.isPlaying() && currentPlayingIndex == position;
            }
            
            // 如果正在播放要删除的曲目，先提示用户
            if (isCurrentlyPlaying) {
                new AlertDialog.Builder(this)
                    .setTitle("警告")
                    .setMessage("此音频正在播放中，删除将会停止播放。确定要删除吗？")
                    .setPositiveButton("确定", (dialog, which) -> {
                        // 停止播放
                        if (isBound) {
                            musicService.stop();
                        }
                        
                        // 执行删除
                        performTrackRemoval(position);
                    })
                    .setNegativeButton("取消", null)
                    .show();
            } else {
                // 如果不是正在播放的曲目，直接删除
                performTrackRemoval(position);
            }
        }
    }
    
    /**
     * 执行音频轨道删除操作
     */
    private void performTrackRemoval(int position) {
        // 删除前检查是否有正在播放的内容
        boolean isPlaying = false;
        int currentPlayingIndex = -1;
        AudioTrack currentTrack = null;
        
        if (isBound && musicService != null) {
            isPlaying = musicService.isPlaying();
            currentPlayingIndex = musicService.getCurrentTrackIndex();
            currentTrack = musicService.getCurrentTrack();
        }
        
        // 删除轨道
        playlist.removeTrack(position);
        
        // 保存播放列表到存储
        PlaylistStorage.savePlaylist(this, playlist);
        Log.d("PlaylistActivity", "删除音频后保存播放列表，共 " + playlist.size() + " 个音频");
        
        // 更新UI
        adapter.notifyDataSetChanged();
        
        // 如果有正在播放的内容且不是被删除的轨道，不更新服务中的播放列表
        if (isPlaying && currentPlayingIndex != position && currentTrack != null) {
            Log.d(TAG, "保持当前播放状态，不更新服务中的播放列表");
        } else if (!isPlaying) {
            // 如果没有正在播放的内容，可以安全地更新播放列表
            if (isBound) {
                musicService.setPlaylist(playlist);
            }
            Log.d(TAG, "没有正在播放的内容，更新服务中的播放列表");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
    
    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // 保存播放列表到存储
        PlaylistStorage.savePlaylist(this, playlist);
        Log.d(TAG, "保存播放列表，共 " + playlist.size() + " 个音频");
        
        // 检查是否有正在播放的内容
        if (isBound && musicService != null && musicService.isPlaying()) {
            int currentIndex = musicService.getCurrentTrackIndex();
            // 不需要在这里重新设置播放位置，因为我们没有改变正在播放的曲目
            Log.d(TAG, "退出时保持当前播放状态，当前播放索引: " + currentIndex);
        }
        
        if (isBound) {
            unbindService(serviceConnection);
            isBound = false;
        }
        super.onDestroy();
    }

    // 播放列表适配器内部类
    private static class PlaylistAdapter extends RecyclerView.Adapter<PlaylistAdapter.ViewHolder> {
        
        interface OnTrackSettingsClickListener {
            void onTrackSettingsClick(int position);
        }
        
        interface OnTrackRemoveClickListener {
            void onTrackRemoveClick(int position);
        }
        
        private final java.util.List<AudioTrack> tracks;
        private final OnTrackSettingsClickListener onTrackSettingsClickListener;
        private final OnTrackRemoveClickListener onTrackRemoveClickListener;
        
        PlaylistAdapter(java.util.List<AudioTrack> tracks, 
                       OnTrackSettingsClickListener onTrackSettingsClickListener,
                       OnTrackRemoveClickListener onTrackRemoveClickListener) {
            this.tracks = tracks;
            this.onTrackSettingsClickListener = onTrackSettingsClickListener;
            this.onTrackRemoveClickListener = onTrackRemoveClickListener;
        }
        
        @Override
        public ViewHolder onCreateViewHolder(android.view.ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_track, parent, false);
            return new ViewHolder(view);
        }
        
        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            AudioTrack track = tracks.get(position);
            holder.tvTrackTitle.setText(track.getTitle());
            holder.tvTrackInfo.setText(String.format("速度: %.1fx, 重复: %d次", 
                    track.getPlaybackSpeed(), track.getRepeatCount()));
            
            holder.itemView.setOnClickListener(v -> {
                if (onTrackSettingsClickListener != null) {
                    onTrackSettingsClickListener.onTrackSettingsClick(holder.getAdapterPosition());
                }
            });
            
            holder.btnDelete.setOnClickListener(v -> {
                if (onTrackRemoveClickListener != null) {
                    onTrackRemoveClickListener.onTrackRemoveClick(holder.getAdapterPosition());
                }
            });
        }
        
        @Override
        public int getItemCount() {
            return tracks.size();
        }
        
        static class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvTrackTitle;
            TextView tvTrackInfo;
            ImageButton btnDelete;
            
            ViewHolder(View itemView) {
                super(itemView);
                tvTrackTitle = itemView.findViewById(R.id.tvTrackTitle);
                tvTrackInfo = itemView.findViewById(R.id.tvTrackInfo);
                btnDelete = itemView.findViewById(R.id.btnDelete);
            }
        }
    }
}
